package com.test.latitudex;

import java.util.HashMap;
import java.util.Map.Entry;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.test.latitudex.utilities.LocationBroadcastReceiver;
import com.test.latitudex.utilities.MyListAdapter;
import com.test.latitudex.utilities.RegistrationManager;

/**
 * A dummy fragment representing a section of the app, but that simply displays dummy text.
 */
public class MyMapFragment extends android.support.v4.app.Fragment {
	/**
	 * The fragment argument representing the section number for this fragment.
	 */
	public static final String ARG_SECTION_NUMBER = "section_number";
	@SuppressWarnings("unused")
	private static final String LOG_TAG = "FriendsActivity";
	int minTime, minDist;

	static String interval = null, duration = null, id = null;
	static Button btn1;
	static Button btn2;
	static Button btn3;
	static EditText et1;
	static EditText et2;
	static EditText et3;
	static TextView tv1;
	static String userId;
	static LocationBroadcastReceiver brc;
	static Context ctx;
	static String lastUpdate = null;
	static boolean serviceStarted = false;
	static GoogleMap map;
	ListView list;
	MyListAdapter adapter;
	static String currentId;
	static FragmentManager fragMan;
	static HashMap<String,Marker> markerMap = new HashMap<String,Marker>();
	
	
	public static boolean setMapPos(String id) {
		if(markerMap.containsKey(id)){
			currentId = id;
			LatLng pos = markerMap.get(id).getPosition();
			markerMap.get(id).getPosition();
			map.animateCamera(CameraUpdateFactory.newLatLng(pos), 1000, null);
			markerMap.get(id).showInfoWindow();
			return true;
		}else{
			return false;
		}
	}

	public static void setMap(){
		SupportMapFragment frm = (SupportMapFragment) (fragMan.findFragmentById(R.id.map));
		if(frm != null){
			map = frm.getMap();
			map.clear();
			currentId = "self";
			//markerVector = new Vector<Marker>();
			markerMap = new HashMap<String,Marker>();
			if(RegistrationManager.getEntity().getSelfData().get(MyListAdapter.KEY_LATITUDE) != null){
				double latitude = Double.parseDouble(RegistrationManager.getEntity().getSelfData().get(MyListAdapter.KEY_LATITUDE));
				double longitude = Double.parseDouble(RegistrationManager.getEntity().getSelfData().get(MyListAdapter.KEY_LONGITUDE));
				LatLng pos = new LatLng(latitude, longitude);
				Marker marker = map.addMarker(new MarkerOptions().position(pos)
						.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
						.title("Current position"));
				 CircleOptions co = new CircleOptions();
		            co.center(pos);
		            co.radius(Double.parseDouble(RegistrationManager.getEntity().getSelfData().get(MyListAdapter.KEY_ACCURACY)));
		            co.fillColor(Color.parseColor("#ccbbffbb"));
		            co.strokeColor(Color.GREEN);
		            co.strokeWidth(1.0f);
		        map.addCircle(co);
				markerMap.put("self",marker);
				marker.showInfoWindow();
				map.moveCamera(CameraUpdateFactory.newLatLngZoom(pos, 10));
			}
			for (HashMap<String, String> subData : RegistrationManager.getEntity().getFriendData()) {
				if(subData.get(MyListAdapter.KEY_LATITUDE) != null){
					double latitude = Double.parseDouble(subData.get(MyListAdapter.KEY_LATITUDE));
					double longitude = Double.parseDouble(subData.get(MyListAdapter.KEY_LONGITUDE));
					LatLng pos = new LatLng(latitude, longitude);
					String label = subData.get(MyListAdapter.KEY_NAME);
					Marker marker = map.addMarker(new MarkerOptions().position(pos).title(label));
					 CircleOptions co = new CircleOptions();
			            co.center(pos);
			            co.radius(Double.parseDouble(subData.get(MyListAdapter.KEY_ACCURACY)));
			            co.fillColor(Color.parseColor("#ccffbbbb"));
			            co.strokeColor(Color.RED);
			            co.strokeWidth(1.0f);
			        map.addCircle(co);
					markerMap.put(subData.get(MyListAdapter.KEY_NAME),marker);
					if(RegistrationManager.getEntity().getSelfData().get(MyListAdapter.KEY_LATITUDE) != null){
						map.moveCamera(CameraUpdateFactory.newLatLngZoom(pos, 10));
					}
				}
			}
			map.animateCamera(CameraUpdateFactory.zoomTo(15), 1000, null);	
		}
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		fragMan = getFragmentManager();
		setMap();
	}

	private static View view;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		if (view != null) {
			ViewGroup parent = (ViewGroup) view.getParent();
			if (parent != null)
				parent.removeView(view);
		}
		try {
			view = inflater.inflate(R.layout.map_activity_layout, container, false);
			Button nextButton = (Button) view.findViewById(R.id.nextButton);
			nextButton.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					boolean getNext = false;
					for(Entry<String, Marker> m : markerMap.entrySet()){
						if(getNext){
							setMapPos(m.getKey());
							return;
						}
						if(m.getKey().equalsIgnoreCase(currentId)){
							getNext = true;
						}
					}
					Entry<String, Marker> rece = (Entry<String, Marker>) markerMap.entrySet().toArray()[0];
					setMapPos(rece.getKey());
				}

			});

			Button prevButton = (Button) view.findViewById(R.id.prevButton);
			prevButton.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					String prevId = null;;
					for(Entry<String, Marker> m : markerMap.entrySet()){
						if(m.getKey().equalsIgnoreCase(currentId)){
							if(prevId == null){
								Entry<String, Marker> rece = (Entry<String, Marker>) markerMap.entrySet().toArray()[markerMap.entrySet().size()-1];
								setMapPos(rece.getKey());
								return;
							}else{
								setMapPos(prevId);
								return;
							}
						}
						prevId = m.getKey();
					}
					
				}

			});
		} catch (InflateException e) {
			/* map is already there, just return view as it is */
		}
		return view;

	}
}